interface from {
  name?: string;
  remark?: string;
  id?: number;
  code?: string;
  isEnable?: number | boolean;
  topLevel?: string;
  top?: string;
  pid?: number;
  son?: number;
  children?: from[];
}
import { PropType } from 'vue';
import {
  addPositionSortList,
  setPositionSortList,
  CheckPositionSortList
} from '@/apis/management/organization/baseSetting/PositionSystem/index';
import { validateRules } from '@/utils/common';
import { Message } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
export default defineComponent({
  emits: ['changeVisible', 'openRefresh'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    oldData: {
      type: Object as PropType<from>,
      default: () => {
        return undefined;
      }
    },
    refresh: {
      type: Boolean,
      default: false
    },
    refreshFn: {
      type: Function,
      default: () => {
        return undefined;
      }
    },
    uniqueCode: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 弹出框标题
    title: {
      type: String
    },
    // 判断用户是新增还是编辑， 新增add 编辑edit
    status: {
      type: String
    }
  },
  setup(props, { emit }) {
    watch(
      () => props.visible,
      async () => {
        if (props.visible) {
          if (!props.oldData) return;
          form.name = cloneDeep(props.oldData.name);
          form.isEnable = props.oldData.isEnable === 1 ? true : false;
          form.remark = props.oldData.remark;
          form.code = cloneDeep(props.oldData.code);
          form.level = props.oldData.level || 0;
          form.id = props.oldData.id;
          form.topLevel = props.oldData.topLevel || '';
          form.top = props.oldData.top || '';
          form.pid = props.oldData.pid || 0;
          console.log('==========================props.oldData==========');
          console.log(props.oldData);
          console.log(form);
          console.log('====================================');
        } else {
          form.name = '';
          form.isEnable = true;
          form.remark = '';
          form.code = '';
          form.id = 0;
          form.level = 0;
          form.pid = 0;
        }
      }
    );
    console.log(props);

    // 获取表单元素
    const refForm = ref();
    // 校验名字查重
    const validateName = async (val: string, cb: any) => {
      try {
        if (val === props.oldData?.name && form.id > 0) {
          //
        } else {
          const data = {
            // type: 1,
            // pid: form.top === '' ? form.pid : form.id,
            name: val
          };
          const res = await validateRules(CheckPositionSortList, data);
          if (res.code) {
            cb(`${res.msg}`);
          }
        }
      } catch (error: unknown) {
        console.log(error);
      }
    };

    // 校验编码查重
    const validateCode = async (val: string, cb: (error?: string) => void) => {
      try {
        if (!/^[A-Z]+$/.test(val)) cb('请输入大写英文字母！');
        if (val === props.oldData?.code && form.id > 0) {
          //
        } else {
          const data = {
            // type: 2,
            // pid: form.top === '' ? form.pid : form.id,
            code: val
          };
          const res = await validateRules(CheckPositionSortList, data);
          if (res.code) {
            cb(`${res.msg}`);
          }
        }
      } catch (error: unknown) {
        console.log(error);
      }
    };
    // 校验
    const rules = reactive({
      name: [
        {
          required: true,
          trigger: "['change', 'input', 'blur']",
          message: '请填写类别名称'
        },
        {
          validator: validateName
        }
      ],
      code: [
        {
          required: true,
          trigger: "['change', 'input', 'blur']",
          message: '请填写类别代码'
        },
        {
          validator: validateCode
        }
      ]
    });

    const handleTitle = () => {
      // if(props.oldData?.top !== '') {
      //   return '编辑子序列'
      // } else if(props.oldData?.top === '') {
      //   return '新增子序列'
      // }
      // if(props.oldData?.topLevel !== ''){
      //   return '编辑序列'
      // }else if(props.oldData.topLevel === ''){
      //   return '新增序列'
      // }
      // if(props.oldData) {
      //   return '编辑职位类别'
      // }else {
      //   return '新增职位类别'
      // }
    };
    // 关闭弹窗
    const handleCancel = () => {
      emit('changeVisible', false);
    };
    // 确认触发
    const handleBeforeOk = async () => {
      if (await refForm.value.validate()) return;
      // if (props.uniqueCode.indexOf(form.code) !== -1)
      //   return Message.error('类别代码重复了');
      if (props.oldData?.name) {
        edit();
      } else {
        add();
      }
      emit('changeVisible', false);
    };
    // 表单数据
    const form = reactive<from>({});
    // 新增
    const add = async () => {
      if (!props.oldData?.id) {
        const { name, code, remark, isEnable } = form;
        const res = await addPositionSortList({
          name,
          code,
          remark,
          isEnable: isEnable ? 1 : 2
        });
        console.log(res);
      } else {
        const { name, code, remark, isEnable, id } = form;
        const res = await addPositionSortList({
          name,
          code,
          remark,
          isEnable: isEnable ? 1 : 2,
          pid: id
        });
        console.log(res);
      }
      emit('openRefresh', true);
    };
    // 编辑
    const edit = async () => {
      if (form.pid) {
        const { name, code, remark, isEnable, id, pid } = form;
        const res = await setPositionSortList({
          name,
          code,
          remark,
          isEnable: isEnable ? 1 : 2,
          id,
          pid
        });
        console.log(res);
      } else {
        const { name, code, remark, isEnable, id } = form;
        const res = await setPositionSortList({
          name,
          code,
          remark,
          isEnable: isEnable ? 1 : 2,
          id
        });
        console.log(res);
      }
      emit('openRefresh', true);
    };
    return () => (
      <a-modal
        width="33%"
        visible={props.visible}
        title-align="center"
        unmount-on-close
        onCancel={handleCancel}
        onOk={handleBeforeOk}
        v-slots={{
          title: () => (
            <div>
              {/* {props.oldData.id ? '编辑' : '新增'}
              职位类别 */}
              {props.title}
            </div>
          )
        }}
      >
        <a-form
          ref={refForm}
          model={form}
          rules={rules}
          auto-label-width={true}
        >
          {form.topLevel ? (
            <a-form-item label="类别名称1：" disabled>
              <a-input style=" width: 350px;" v-model={form.topLevel} />
            </a-form-item>
          ) : (
            ''
          )}
          {form.top ? (
            <a-form-item label="序列名称2：" disabled>
              <a-input style=" width: 350px;" v-model={form.top} />
            </a-form-item>
          ) : (
            ''
          )}
          <a-form-item
            field="name"
            required
            v-slots={{
              label: () => {
                return (
                  <>
                    {form.topLevel
                      ? form.top
                        ? '子序列名称3：'
                        : '序列名称4：'
                      : '类别名称5：'}
                  </>
                );
              }
            }}
          >
            <a-input style=" width: 350px;" v-model={form.name} />
          </a-form-item>
          {(form.level === 0 && props.status === 'add') ||
          (form.level === 1 && props.status === 'edit') ? (
            <a-form-item field="code" label="类别代码：" required>
              <a-input style=" width: 350px;" v-model={form.code} />
            </a-form-item>
          ) : (
            ''
          )}

          <a-form-item field="isEnable" label="启用状态：">
            <a-switch v-model={form.isEnable} />
          </a-form-item>
          <a-form-item label="描述：">
            <a-textarea
              v-model={form.remark}
              allow-clear
              style=" width: 400px;"
              auto-size={{
                minRows: 8,
                maxRows: 8
              }}
            />
          </a-form-item>
        </a-form>
      </a-modal>
    );
  }
});
